package com.briup.prs;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;

public class Step1 extends Configured implements Tool {
    public static class Step1Mapper extends Mapper<LongWritable, Text,Text, DoubleWritable>{

        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
//            将读到的文本行 value 先转toString  然后再切割  数组 四个元素  用户  商品  行为 时间戳
            String[] arr = value.toString().split("[,]");
            double val=0;
           if("showShop".equals(arr[2])||"showProduct".equals(arr[2])) {
               val=0.05;
           }else if ("addCart".equals(arr[2])||"addShopCar".equals(arr[2])){
               val=0.15;
           }else if ("createOrder".equals(arr[2])){
               val=0.3;
           }else if("paySuccess".equals(arr[2])){
               val=0.5;
           }
//           拼接用户 和商品 编号成为k2
            String outKey = arr[0] + ":" + arr[1];
            context.write(new Text(outKey),new DoubleWritable(val));
        }
    }
    public static class Step1Reducer extends Reducer<Text,DoubleWritable,Text,DoubleWritable>{
        @Override
        protected void reduce(Text key, Iterable<DoubleWritable> values, Context context) throws IOException, InterruptedException {
            double sum=0;
            for (DoubleWritable value : values) {
                sum+=value.get();
            }
            context.write(key,new DoubleWritable(sum));

        }
    }
    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = getConf();
        String in = conf.get("in");
        String out = conf.get("out");

        Job job = Job.getInstance(conf);
        job.setJobName("Step1");
        job.setJarByClass(this.getClass());

        TextInputFormat.addInputPath(job,new Path(in));
        job.setMapperClass(Step1Mapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(DoubleWritable.class);

        job.setReducerClass(Step1Reducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(DoubleWritable.class);

        TextOutputFormat.setOutputPath(job,new Path(out));


        return job.waitForCompletion(true)?0:-1;
    }

    public static void main(String[] args) throws Exception {
        ToolRunner.run(new Step1(),args);
    }
}
